package com.xyj.data.data_controller_demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xyj.data.data_controller_demo.dataFilter.modle.ResultInfo;
import com.xyj.data.data_controller_demo.domain.DemoUser;
import com.xyj.data.data_controller_demo.request.LoginRequest;
import com.xyj.data.data_controller_demo.service.DemoUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

/**
 * @author xyj
 * @date 2023/12/20
 */
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    DemoUserService demoUserService;

    @GetMapping("/getAllUser")
    public ResultInfo getAllUser() {
        log.info("获取所有用户信息");
        return ResultInfo.success(demoUserService.list());
    }

    @PostMapping("/login")
    public ResultInfo login(@RequestBody LoginRequest loginRequest) {
        log.info("用户登录");
        DemoUser one = demoUserService.getOne(new LambdaQueryWrapper<DemoUser>().eq(DemoUser::getName, loginRequest.getUsername())
                .eq(DemoUser::getPassword, loginRequest.getPassword()));
        if (one == null) {
            return ResultInfo.error("用户名或密码错误");
        }
        if (StringUtils.isEmpty(one.getToken())) {
            one.setToken(UUID.randomUUID().toString());
            demoUserService.updateById(one);
        }
        return ResultInfo.success(one.getToken());
    }
}
